<?php

namespace app\siteadmin\service;

use app\siteadmin\model\User;
use app\Response;
use think\facade\Cache;

class AdminLoginService
{
    /***
     * 登录
    */
    public static function login($data)
    {
        $where[] = ["username|phone","like","%".$data["account"]."%"];
        $find = User::info($where);
        if(!empty($find)){
            $find = $find->toArray();
            $encryption = $find['encryption'];
        }
        else{
            return Response::wrapError(0,'用户名密码错误');
        }

        if($find['type'] != 10&&$find['type'] != 11){
            return Response::wrapError(0,'该用户不为网点后台管理员');
        }

        $password = self::encPassword($data["password"],$encryption);//密码
        $find_info =  User::find_info($data["account"],$password);
        if(!$find_info){
            return Response::wrapError(0,'用户名密码错误2');
        }
        if(!empty($find_info)){
            $find_info = $find_info->toArray();
        }
        if($find_info['enable'] == 0){
            return Response::wrapError(0,'账号被锁定');
        }
        User::lasttime($find_info['uid']);

        session('uid', $find_info['uid']);
        session('username', $data["account"]);
        session('type', $find_info['type']);

        $info = [];
        $info['uid'] = $find_info['uid'];
        $info['username'] =  $data["account"];
        $info['type'] =  $find_info['type'];
        if($info['type'] == 11){
            $info["paid"] = $find_info['paid'];
        }elseif($info['type'] == 10){
            $info["paid"] = $find_info['uid'];
        }
        $newStr = self::str_random(8);
        if (Cache::has("admin-token".$info["uid"])){
            Cache::set("admin-token".$info["uid"],"");
            Cache::set("admin-token".$info["uid"],$newStr,43200);
        }else{
            Cache::set("admin-token".$info["uid"],$newStr,43200);
        }
        $info['auth_token'] = $newStr;
        return Response::wrapData($info);
    }




    //密码加密
    public static function encPassword($password,$encryption){
        $enc = md5(md5($password).$encryption);
        return $enc;
    }


    public static function str_random($length = 16)
    {
        $string = '';
        while (($len = strlen($string)) < $length) {
            $size = $length - $len;
            $bytes = random_bytes($size);
            $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
        }
        return $string;
    }


    /**
     * 生成随机字符串
     * @param int $length
     * @return string
     */
    public static function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }


}